﻿namespace wwm.LeetCodeHelper;
/// <summary>
/// 
/// </summary>
public class CompareProvider<T> : IComparer<T> where T : IComparable
{
    private static readonly TypeInfo NullableTypeInfo = typeof(Nullable<>).GetTypeInfo();

    public int Compare(T x, T y)
    {
        TypeInfo typeInfo = typeof(T).GetTypeInfo();
        //if (typeInfo.IsValueType)
        //{
        //    return x.Equals(y) ? 0 : -1;
        //}
        if (!typeInfo.IsValueType || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().GetTypeInfo().IsAssignableFrom(NullableTypeInfo)))
        {
            if (object.Equals(x, default(T)))
            {
                if (object.Equals(y, default(T)))
                {
                    return 0;
                }
                return -1;
            }
            if (object.Equals(y, default(T)))
            {
                return -1;
            }
        }
        if ((object)x.GetType() != y.GetType())
        {
            return -1;
        }
        return (x as IComparable<T>)?.CompareTo(y) ?? x.CompareTo(y);
    }
}

